package top.rushpeak.edu03.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import top.rushpeak.edu03.api.model.User;
import top.rushpeak.edu03.api.service.BasicService;
import top.rushpeak.edu03.api.service.HelloService;
import top.rushpeak.edu03.core.cache.CacheEntity;
import top.rushpeak.edu03.core.cache.RedisClientTemplate;
import top.rushpeak.edu03.core.enums.CacheType;
import top.rushpeak.edu03.core.exception.BusinessException;
import top.rushpeak.edu03.core.mq.EventEnum;
import top.rushpeak.edu03.core.mq.MessageSender;
import top.rushpeak.edu03.core.util.SerializeUtil;
import top.rushpeak.edu03.dao.UserDao;

@Service
public class HelloServiceImpl extends BasicService implements HelloService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RedisClientTemplate<String,byte[]> redisClientTemplate;
	
	@Autowired
	private MessageSender messageSender;
	
	@Override
	public String say() {
		System.out.println("hello_service");
		LOG.info("hello_service");
		return "hello,service:"+DateUtil.formatDate(new Date(),"yyyyMMddHHmmss");
	}

	@Override
	public User findUser(String userName) {
		return userDao.findUserByUserName(userName);
	}

	@Override
	public User findRedisUser(String userName) {
		try {
			
			User user = (User)SerializeUtil.unserialize(redisClientTemplate.get(new CacheEntity(userName, CacheType.JSessionID)));
			if(user==null){
				User userRedid = userDao.findUserByUserName(userName);
				if(userRedid!=null){
					
					redisClientTemplate.put(new CacheEntity(userName, CacheType.JSessionID), SerializeUtil.serialize(userRedid), 30, TimeUnit.MINUTES);
					return userRedid;
				}
			}
			return user;
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public void testMQ(String msg) {
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("testMQ", msg);
		messageSender.sendQueueMessage(EventEnum.TEST1, map);
		
	}

	@Override
	public void testMQ2(String msg) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("testMQ2", msg);
		messageSender.sendQueueMessage(EventEnum.TEST2, map);
	}

	@Override
	public void testJob() {
		LOG.info("定时任务执行中");
		System.out.println("输出执行任务");
		
	}
	
	
	
	
	
	

}
